package com.shanks.home.module.multythread;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

import com.shanks.home.R;

/**
 * @author Shanks
 * @time 2013.11.21
 */
public class ShanksAsyncTaskActivity extends Activity {

	private Context context;
	private Button loadImgBtn;
	private ImageView imageIV;
	private String imagePath = "http://ww3.sinaimg.cn/mw600/be4161d4tw1e2iuqwa7pcj.jpg";
	private ProgressDialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		context = getBaseContext();
		this.setContentView(R.layout.acvitity_asynctask);
		initView();
	}

	private void initView() {
		loadImgBtn = (Button)this.findViewById(R.id.asynctask_loadimg_btn);
		imageIV = (ImageView)this.findViewById(R.id.asynctask_image_iv);

		dialog = new ProgressDialog(this);
		dialog.setTitle(context.getResources().getString(R.string.asynctask_prompt));
		dialog.setMessage(context.getResources().getString(R.string.asynctask_isLoading));
		dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		dialog.setCancelable(false);
		
		loadImgBtn.setOnClickListener(onClickListener);
	}

	private OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			int id = v.getId();
			if (id == R.id.asynctask_loadimg_btn) {
				testAsyncTask();
			}
		}
	};

	private void testAsyncTask() {
		new MyTask().execute(imagePath);
	}

	/**
	 * 使用异步任务的规则：
	 * 1、声明一个类继承AsyncTask，标注3个参数类型
	 * 2、第一个参数表示要执行的任务通常是网络路径，第二个参数表示进度的刻度，第三个参数表示执行任务的返回结果
	 */
	private class MyTask extends AsyncTask<String, Integer, Bitmap> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog.show();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			dialog.setProgress(values[0]);
		}
		
		// 主要是完成耗时操作
		@Override
		protected Bitmap doInBackground(String... params) {
			Bitmap bitmap = null;
			HttpClient httpClient = new DefaultHttpClient();
			HttpClientParams.setCookiePolicy(httpClient.getParams(), CookiePolicy.BROWSER_COMPATIBILITY);
			HttpGet httpGet = new HttpGet(params[0]);
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			InputStream inputStream = null;
			try {
				HttpResponse httpResponse = httpClient.execute(httpGet);
				inputStream = httpResponse.getEntity().getContent();
				if (httpResponse.getStatusLine().getStatusCode() == 200) {
//					HttpEntity httpEntity = httpResponse.getEntity();
//					byte[] data = EntityUtils.toByteArray(httpEntity);
//					bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
					int len = 0;
					byte[] data = new byte[1024];
					int total_len = 0;
					long file_length = httpResponse.getEntity().getContentLength();
					while ((len = inputStream.read(data)) != -1) {
						total_len += len;
						int value = (int) ((total_len / (float)file_length) * 100);
						publishProgress(value);
						outputStream.write(data, 0, len);
					}
					byte[] result = outputStream.toByteArray();
					bitmap = BitmapFactory.decodeByteArray(result, 0, result.length);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (inputStream != null) {
					try {
						inputStream.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			return bitmap;
		}

		// 主要完成UI更新
		@Override
		protected void onPostExecute(Bitmap result) {
			super.onPostExecute(result);
			dialog.dismiss();
			imageIV.setImageBitmap(result);
		}
	}
}